package com.fengqilin.projectlplc;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.text.DecimalFormat;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, Client.Callback {

    static MainActivity mainActivity;
    boolean isEnable = false;
    boolean[] enableArr = {true, true};
    public static String nowKey = "98DA";
    int[] ids = {R.id.D00107, -1, R.id.D02522, R.id.D02524, R.id.D00740, R.id.D00112, R.id.D002516, -1, -1};
    int D112 = 0;
    float ratio = 10000F;

    boolean D00112_onFocusChange = false;
    boolean D002516_onFocusChange = false;
    boolean D00740_onFocusChange = false;

    private static final String TAG = MainActivity.class.getName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mainActivity = this;
        setContentView(R.layout.activity_main);
        initView();
        setText(ids[0], "连接中...");
    }

    private void setEnable(boolean isEnable) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                setTextView(R.id.D00112_UP, isEnable);
                findViewById(R.id.D00112).setEnabled(isEnable);
//        setColor(R.id.D00112, 0);
                setTextView(R.id.D00112_DOWN, isEnable);
                setTextView(R.id.D002516_0_1, isEnable);
                setTextView(R.id.D002516_1, isEnable);
                findViewById(R.id.D002516).setEnabled(isEnable);
//        setColor(R.id.D002516, 0);
                setTextView(R.id.I00112, isEnable);
                setTextView(R.id.I00113, isEnable);
                setTextView(R.id.I00081, isEnable);
                setTextView(R.id.I00082, isEnable);
                findViewById(R.id.D00740).setEnabled(isEnable);
//        setColor(R.id.D00740, 0);
            }
        });

    }

    private void setTextView(int id, boolean isEnable) {
        TextView D00112_DOWN = findViewById(id);
        D00112_DOWN.setEnabled(isEnable);
        setColor(id, 0);
        D00112_DOWN.setTextColor(isEnable ? Color.BLACK : Color.WHITE);
    }

    private void initView() {
        setEnable(false);
        findViewById(R.id.D00107).setOnClickListener(this);
        findViewById(R.id.D00112_UP).setOnClickListener(this);
        findViewById(R.id.D00112_DOWN).setOnClickListener(this);

        findViewById(R.id.D002516_0_1).setOnClickListener(this);
        findViewById(R.id.D002516_1).setOnClickListener(this);

        findViewById(R.id.I00112).setOnClickListener(this);
        findViewById(R.id.I00113).setOnClickListener(this);

        findViewById(R.id.I00081).setOnClickListener(this);
        findViewById(R.id.I00082).setOnClickListener(this);
        setEditTextEnable(R.id.D00112, false);
        setEditTextEnable(R.id.D00740, false);
        setEditTextEnable(R.id.D002516, false);
        findViewById(R.id.D00112).setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                EditText editText = findViewById(R.id.D00112);
                if (b) editText.setText("");
                else hideKeyboard(editText);
//                D00740_onFocusChange = false;
//                D002516_onFocusChange = false;
                D00112_onFocusChange = b;
            }
        });
        findViewById(R.id.D00740).setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                EditText editText = findViewById(R.id.D00740);
                if (b) editText.setText("");
                else hideKeyboard(editText);
                D00740_onFocusChange = b;
//                D002516_onFocusChange = false;
//                D00112_onFocusChange = false;
            }
        });
        findViewById(R.id.D002516).setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                EditText editText = findViewById(R.id.D002516);
                if (b) editText.setText("");
                else hideKeyboard(editText);
//                D00740_onFocusChange = false;
                D002516_onFocusChange = b;
//                D00112_onFocusChange = false;
            }
        });
        ((EditText) findViewById(R.id.D00112)).setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                findViewById(R.id.D00112).clearFocus();
                if (!isEnable) {
                    showToast("状态不可用");
                    return false;
                }
                String trim = textView.getText().toString().trim();
                if (TextUtils.isEmpty(trim)) {
                    showToast("输入不能为为空");
                    return false;
                }
                int i1 = Integer.parseInt(trim);
                if (i1 < 0) {
                    showToast("输入不能为负数");
                    return false;
                }
                request("D112", i1);
                return false;
            }
        });
        ((EditText) findViewById(R.id.D00740)).setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                findViewById(R.id.D00740).clearFocus();
                if (!isEnable) {
                    showToast("状态不可用");
                    return false;
                }
                String trim = textView.getText().toString().trim();
                if (TextUtils.isEmpty(trim)) {
                    showToast("输入不能为为空");
                    return false;
                }
                int i1 = Integer.parseInt(trim);
                if (i1 < 0) {
                    showToast("输入不能为负数");
                    return false;
                }
                request("D740", i1);
                return false;
            }
        });
        ((EditText) findViewById(R.id.D002516)).setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                findViewById(R.id.D002516).clearFocus();
                if (!isEnable) {
                    showToast("状态不可用");
                    return false;
                }
                String trim = textView.getText().toString().trim();
                if (TextUtils.isEmpty(trim)) {
                    showToast("输入不能为为空");
                    return false;
                }
                try {
                    float i1 = Float.parseFloat(trim);
                    if (i1 < 0) {
                        showToast("输入不能为负数");
                        return false;
                    }
                    setLog((int) (i1 * ratio) + "");
                    request("D2516", (int) (i1 * ratio));
                } catch (Exception e) {
                    setErrorLog(e.getMessage());
                }
                return false;
            }
        });
    }

    public void setEditTextEnable(int id, boolean enable) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                EditText editText = findViewById(id);
                editText.clearFocus();
                editText.setFocusable(enable);
                editText.setFocusableInTouchMode(enable);
                editText.setCursorVisible(enable);
            }
        });
    }

    public void showToast(String txt) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this, txt, Toast.LENGTH_LONG).show();
            }
        });
    }

    int I112 = 0;
    int I113 = 0;
    int I81 = 0;
    int I82 = 0;

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.D00107) {
            Client.requestAll(this);
        }
        if (!isEnable) {
            showToast("状态不可用");
            return;
        }
        if (view.getId() == R.id.D00112_UP) {
            D112--;
            request("D112", D112);
        } else if (view.getId() == R.id.D00112_DOWN) {
            D112++;
            request("D112", D112);
        } else if (view.getId() == R.id.I00112) {
            request("I112", I112 == 0 ? 1 : 0);
        } else if (view.getId() == R.id.I00113) {
            request("I113", I113 == 0 ? 1 : 0);
        } else if (view.getId() == R.id.I00081) {
            request("I81", I81 == 0 ? 1 : 0);
        } else if (view.getId() == R.id.I00082) {
            request("I82", I82 == 0 ? 1 : 0);
        } else if (view.getId() == R.id.D002516_0_1) {
            request("D2516", (int) ratio / 10);
        } else if (view.getId() == R.id.D002516_1) {
            request("D2516", (int) ratio);
        }
    }

    public void request(String cmd, int value) {
        if (value < 0) {
            showToast("输入不能为负数");
            return;
        }
        int index = 0;
        Integer integer = Client.inst().initKeyMap().get(cmd);
        if (integer != null) {
            index = integer;
        } else {
            Log.e(TAG, "initKeyMap not exits code " + cmd);
        }
        cmd = Utils.appendCmd(cmd, value);
        Client.request(cmd, index, this);
//        Client.request("01WWRD00135,01,0004\r\n", 1, this);
    }

    @Override
    public void onResult(int index, String data) {
        Log.d(TAG, "index" + index + ": " + data);
        if (TextUtils.isEmpty(data)) {
            setText(ids[0], "连接错误机台");
            if (isEnable) {
                setEnable(false);
            }
            isEnable = false;
            return;
        }
        // 校验key和开机状态
        switch (index) {
            case 0:
                if (!nowKey.equals(data.substring(4))) {
                    setText(ids[0], "连接错误机台");
                    if (isEnable) {
                        setEnable(false);
                    }
                    isEnable = false;
                    enableArr[0] = false;
                } else {
                    enableArr[0] = true;
                }
                break;
            case 1:
                boolean isOldEnable = isEnable;
                int code = -1;
                String dataCode = data.substring(4);
                if (!TextUtils.isEmpty(dataCode)) {
                    code = Integer.parseInt(dataCode);
                    // Log.d(TAG, "setEnable: " + isEnable);
                    // Log.d(TAG, "setEnable: " + code);
                }
                if (code != 0) {
                    setText(ids[0], "开机中...");
                    if (isEnable) {
                        setEnable(false);
                    }
                    isEnable = false;
                    enableArr[1] = false;
                } else {
                    if (!isEnable) {
                        setEnable(true);
                    }
                    enableArr[1] = true;
                    isEnable = enableArr[0];
                    setText(ids[0], "连接成功");
                }
                if (isOldEnable != enableArr[0] || isOldEnable != enableArr[1]) {
                    setEditTextEnable(R.id.D00112, isEnable);
                    setEditTextEnable(R.id.D00740, isEnable);
                    setEditTextEnable(R.id.D002516, isEnable);
                }
                break;
            case 2: // 当前命令值
            case 3: // 编码器反馈值
                setHexText(ids[index], data);
                break;
            case 4:
                if (!D00740_onFocusChange) {
                    try {
                        // 第几组
                        setEditText(ids[4], Integer.parseInt(data.substring(4), 16) + "");
                    } catch (Exception e) {
                        setLog("第几组:" + e.getMessage());
                    }
                }
                break;
            case 5:
                if (!D00112_onFocusChange) {
                    try {
                        // 伺服号
                        D112 = Integer.parseInt(data.substring(4), 16);
                        setEditText(ids[5], D112 + "");
                    } catch (Exception e) {
                        setLog("伺服号:" + e.getMessage());
                    }
                }
                break;
            case 6:
                if (!D002516_onFocusChange) {
                    try {
                        // 微调值
                        setHexEditText(ids[6], data);
                    } catch (Exception e) {
                        setLog("微调值:" + e.getMessage());
                    }
                }
                break;
            case 8:
                try {
                    // 前进后退状态
                    String state2 = data.substring(4);
                    I112 = Integer.parseInt(state2.charAt(0) + "");
                    I113 = Integer.parseInt(state2.charAt(1) + "");
                    setColor(R.id.I00112, I112);
                    setColor(R.id.I00113, I113);
                } catch (Exception e) {
                    setLog("前进后退状态:" + e.getMessage());
                }
                break;
            case 7:
                try {
                    // 微调状态
                    String state1 = data.substring(4);
                    I81 = Integer.parseInt(state1.charAt(0) + "");
                    I82 = Integer.parseInt(state1.charAt(1) + "");
                    setColor(R.id.I00081, I81);
                    setColor(R.id.I00082, I82);
                } catch (Exception e) {
                    setLog("微调状态:" + e.getMessage());
                }
                break;
            default:
                break;
        }
    }

    private void setColor(int id, int state) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (state == 1) findViewById(id).setBackgroundColor(Color.GREEN);
                else {
                    findViewById(id).setBackgroundResource(R.color.bg);
                }
            }
        });
    }

    private String int2Hex(String data) {
        String txt = "";
        try {
            String hexString = data.substring(4);
            hexString = hexString.substring(4) + "" + hexString.substring(0, 4);
            float lHexString = ((int) (0xFFFFFFFFL & Long.parseLong(hexString, 16))) / ratio;
            txt = new DecimalFormat("0.0000").format(lHexString);
        } catch (Exception e) {
            setErrorLog("int2Hex:" + data + "=>" + e.getMessage());
        }
        return txt;
    }

    private void setHexText(int id, String data) {
        setText(id, int2Hex(data));
    }

    private void setHexEditText(int id, String data) {
        setEditText(id, int2Hex(data));
    }

    private void setText(int id, String str) {
        if (!TextUtils.isEmpty(str)) runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ((TextView) findViewById(id)).setText(str);
            }
        });
    }

    private void setEditText(int id, String str) {
        if (!TextUtils.isEmpty(str)) runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ((EditText) findViewById(id)).setText(str);
            }
        });
    }

    private void setLog(String str) {
        Log.d(TAG, "setLog: " + str);
    }

    private void setErrorLog(String str) {
        Log.d(TAG, "setErrorLog: " + str);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Client.isStart = true;
        Client.requestAll(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        Client.isStart = false;
        Client.p.stopPolling();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void hideKeyboard(EditText editText) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }
}